{% extends "base.html" %}

{% block head %}
<!-- 使用本地ECharts库 -->
<script src="{{ url_for('static', filename='js/echarts.min.js') }}"></script>

<style>
    :root {
        --primary-color: #1976d2;
        --primary-hover: #1565c0;
        --border-color: #e0e0e0;
        --light-gray: #f5f5f5;
        --text-color: #333;
        --shadow-color: rgba(0, 0, 0, 0.1);
    }

    body {
        color: var(--text-color);
        background-color: #f8f9fa;
    }

    .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
    }

    /* 卡片样式 */
    .card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px var(--shadow-color);
        padding: 20px;
        margin-bottom: 20px;
    }

    .card-header {
        margin: -20px -20px 20px;
        padding: 15px 20px;
        background: var(--light-gray);
        border-radius: 8px 8px 0 0;
        border-bottom: 1px solid var(--border-color);
    }

    .card-header h2 {
        margin: 0;
        font-size: 1.5rem;
        color: var(--primary-color);
    }

    .card-header h5 {
        margin: 0;
        font-size: 1.1rem;
        color: var(--text-color);
    }

    /* 表单样式 */
    .form-group {
        margin-bottom: 20px;
    }

    .form-label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
    }

    .checkbox-group {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        gap: 12px;
        padding: 10px;
        background-color: var(--light-gray);
        border-radius: 4px;
    }

    .form-check {
        display: flex;
        align-items: center;
        padding: 8px 16px;
        background: white;
        border-radius: 4px;
        transition: background-color 0.2s;
        min-width: 120px;
    }

    .form-check:hover {
        background-color: var(--light-gray);
    }

    .form-check-input {
        margin-right: 10px;
    }

    .form-check-label {
        font-size: 14px;
        user-select: none;
        margin-bottom: 0;
        cursor: pointer;
        white-space: nowrap;
    }

    /* 文件夹列表样式 */
    .folder-list {
        max-height: 300px;
        overflow-y: auto;
        background-color: var(--light-gray);
        border-radius: 4px;
        padding: 10px;
    }

    .folder-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 8px;
        background: white;
        border-radius: 4px;
        margin-bottom: 8px;
        transition: background-color 0.2s;
    }

    .folder-item:last-child {
        margin-bottom: 0;
    }

    .folder-item:hover {
        background-color: var(--light-gray);
    }

    .folder-item-left {
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .folder-item input[type="checkbox"] {
        margin: 0;
    }

    .folder-item label {
        margin: 0;
        cursor: pointer;
        font-size: 14px;
    }

    /* 文本颜色样式 */
    .text-danger {
        color: #dc3545 !important;
    }

    .text-warning {
        color: #fd7e14 !important;
    }

    .text-secondary {
        color: #6c757d !important;
    }

    .text-success {
        color: #28a745 !important;
    }

    .text-primary {
        color: #007bff !important;
    }

    /* 滚动条样式 */
    .folder-list::-webkit-scrollbar {
        width: 8px;
    }

    .folder-list::-webkit-scrollbar-track {
        background: var(--light-gray);
        border-radius: 4px;
    }

    .folder-list::-webkit-scrollbar-thumb {
        background: var(--primary-color);
        border-radius: 4px;
    }

    .folder-list::-webkit-scrollbar-thumb:hover {
        background: var(--primary-hover);
    }

    /* 按钮样式 */
    .btn-group {
        margin-top: 15px;
        display: flex;
        gap: 10px;
    }
    
    .btn {
        padding: 8px 16px;
        border-radius: 4px;
        border: none;
        cursor: pointer;
        font-weight: 500;
        transition: background-color 0.2s;
    }
    
    .btn-primary {
        background-color: var(--primary-color);
        color: white;
    }
    
    .btn-primary:hover {
        background-color: var(--primary-hover);
    }
    
    .btn-secondary {
        background-color: #6c757d;
        color: white;
    }
    
    .btn-secondary:hover {
        background-color: #5a6268;
    }
    
    .btn:disabled {
        opacity: 0.65;
        cursor: not-allowed;
    }
    
    /* 状态标签样式 */
    .status-badge {
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        margin-left: 8px;
    }
    
    .status-exists {
        background-color: #d4edda;
        color: #155724;
    }
    
    .status-not-exists {
        background-color: #f8d7da;
        color: #721c24;
    }
    
    /* Loading spinner */
    .spinner {
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid var(--primary-color);
        border-radius: 50%;
        animation: spin 1s linear infinite;
        display: none;
        margin-left: 10px;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    /* 状态说明样式 */
    .action-bar {
        padding: 10px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px var(--shadow-color);
    }

    .status-legend {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }

    /* 文件夹状态列表样式 */
    #folderStatus {
        background: white;
        border-radius: 8px;
        padding: 10px;
        box-shadow: 0 2px 4px var(--shadow-color);
    }

    .folder-status-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px;
        border-bottom: 1px solid var(--border-color);
    }

    .folder-status-item:last-child {
        border-bottom: none;
    }

    .folder-name {
        font-weight: 500;
    }

    /* 表格容器样式优化 */
    .table-wrapper {
        position: relative;
        margin: 20px -20px;
        background: white;
    }

    .table-container {
        width: 100%;
        overflow-x: auto;
        position: relative;
        max-height: 600px;
        overflow-y: auto;
        scrollbar-width: thin;
        scrollbar-color: var(--primary-color) var(--light-gray);
    }

    /* 自定义滚动条样式 */
    .table-container::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }

    .table-container::-webkit-scrollbar-track {
        background: var(--light-gray);
        border-radius: 4px;
    }

    .table-container::-webkit-scrollbar-thumb {
        background: var(--primary-color);
        border-radius: 4px;
    }

    .table-container::-webkit-scrollbar-thumb:hover {
        background: var(--primary-hover);
    }

    /* 滑动指示器 */
    .scroll-indicator {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(0, 0, 0, 0.5);
        color: white;
        padding: 8px;
        border-radius: 4px;
        font-size: 12px;
        opacity: 0;
        transition: opacity 0.3s;
        pointer-events: none;
    }

    .scroll-indicator.visible {
        opacity: 1;
    }

    /* 表格样式优化 */
    .result-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
        margin: 0;
        font-size: 14px;
        min-width: 1200px;
    }

    .result-table th {
        background: #e6f7ff;
        color: #0050b3;
        font-weight: 500;
        position: sticky;
        top: 0;
        z-index: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        min-width: 120px;
        padding: 12px 8px;
        border: 1px solid #d9d9d9;
        border-bottom: 2px solid #1890ff;
        text-align: left;
    }

    .result-table td {
        border: 1px solid #d9d9d9;
        padding: 8px;
        text-align: left;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 200px;
        background: white;
    }

    .result-table tr:nth-child(even) {
        background-color: #fafafa;
    }

    .result-table tr:hover td {
        background-color: #e6f7ff;
    }

    .result-table td:hover {
        overflow: visible;
        white-space: normal;
        word-break: break-all;
        position: relative;
        z-index: 2;
        background: #fff;
        box-shadow: 0 2px 8px rgba(0,0,0,0.15);
    }

    /* 分页控件美化 */
    .pagination-container {
        background: white;
        padding: 16px;
        border-top: 1px solid var(--border-color);
        border-radius: 0 0 8px 8px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    #total-records {
        color: #666;
        font-size: 14px;
    }

    .pagination {
        display: flex;
        gap: 8px;
        align-items: center;
    }

    .pagination button {
        min-width: 32px;
        height: 32px;
        padding: 0 8px;
        border: 1px solid #d9d9d9;
        border-radius: 2px;
        background: white;
        color: rgba(0, 0, 0, 0.85);
        font-size: 14px;
        line-height: 30px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;
        user-select: none;
    }

    .pagination button:hover:not(:disabled) {
        color: #40a9ff;
        border-color: #40a9ff;
    }

    .pagination button:disabled {
        color: rgba(0, 0, 0, 0.25);
        border-color: #d9d9d9;
        background-color: #f5f5f5;
        cursor: not-allowed;
    }

    .pagination button.active {
        color: #fff;
        background: #1890ff;
        border-color: #1890ff;
    }

    .pagination-ellipsis {
        color: rgba(0, 0, 0, 0.25);
        padding: 0 8px;
        line-height: 32px;
    }

    /* 字段选择模态框样式 */
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1000;
    }

    .modal.visible {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .modal-content {
        background-color: white;
        padding: 24px;
        border-radius: 8px;
        width: 90%;
        max-width: 800px;
        max-height: 90vh;
        overflow-y: auto;
        position: relative;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 16px;
        border-bottom: 1px solid var(--border-color);
    }

    .modal-title {
        font-size: 20px;
        font-weight: 600;
        color: var(--text-color);
        margin: 0;
    }

    .modal-close {
        background: none;
        border: none;
        font-size: 24px;
        color: var(--text-color);
        cursor: pointer;
        padding: 4px;
        line-height: 1;
    }

    .modal-close:hover {
        color: var(--primary-color);
    }

    .modal-body {
        margin-bottom: 20px;
    }

    .modal-footer {
        display: flex;
        justify-content: flex-end;
        gap: 12px;
        padding-top: 16px;
        border-top: 1px solid var(--border-color);
    }

    /* 字段选择网格样式 */
    .field-selection-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 10px;
        margin-top: 10px;
    }

    .field-checkbox {
        display: flex;
        align-items: center;
        padding: 8px;
        background: var(--light-gray);
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.2s;
    }

    .field-checkbox:hover {
        background-color: var(--menu-hover);
    }

    .field-checkbox input {
        margin-right: 8px;
    }

    /* 按钮组样式 */
    .button-group {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 20px;
    }

    .button-group > * {
        margin: 0 !important;
    }

    /* 下载按钮样式 */
    .download-btn {
        margin-top: 0 !important;
    }

    /* 添加操作按钮组样式 */
    .action-buttons {
        display: flex;
        align-items: center;
        gap: 15px;
        margin-bottom: 20px;
    }

    /* 添加状态标签样式 */
    .dict-status {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 14px;
        margin-left: 10px;
    }

    .dict-status.exists {
        background-color: #e8f5e9;
        color: #2e7d32;
    }

    .dict-status.not-exists {
        background-color: #ffebee;
        color: #c62828;
    }

    .dict-status.generating {
        background-color: #fff3e0;
        color: #ef6c00;
        animation: pulse 1.5s infinite;
    }

    @keyframes pulse {
        0% { opacity: 1; }
        50% { opacity: 0.6; }
        100% { opacity: 1; }
    }

    /* 修改按钮组样式 */
    .button-group {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 20px;
    }

    .button-group > * {
        margin: 0 !important;
    }

    /* 修改字段选择按钮样式 */
    .field-select-btn {
        margin-left: 0 !important;
    }

    /* 添加文件夹状态样式 */
    .folder-status {
        display: inline-block;
        padding: 2px 6px;
        border-radius: 3px;
        font-size: 12px;
        margin-left: 8px;
    }

    .folder-status.exists {
        background-color: #e8f5e9;
        color: #2e7d32;
    }

    .folder-status.not-exists {
        background-color: #ffebee;
        color: #c62828;
    }

    /* 修改字段选择和下载按钮组样式 */
    .form-group {
        margin-bottom: 20px;
    }

    .button-group {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .button-group > * {
        margin: 0 !important;
    }

    /* 修改字段选择按钮样式 */
    .field-select-btn {
        margin-left: 0 !important;
    }

    /* 修改下载按钮样式 */
    .download-btn {
        margin-top: 0 !important;
    }

    /* 修改按钮基础样式 */
    .btn {
        display: inline-block;
        padding: 8px 16px;
        font-size: 14px;
        font-weight: 500;
        text-align: center;
        text-decoration: none;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.2s;
        border: 1px solid transparent;
    }

    .btn-outline-primary {
        background-color: transparent;
        border-color: var(--primary-color);
        color: var(--primary-color);
    }

    .btn-outline-primary:hover {
        background-color: var(--primary-color);
        color: white;
    }

    .d-flex.justify-content-between.mb-4 {
        margin-top: 2rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="card">
        <div class="card-header">
            <h2>人员关系网络分析</h2>
        </div>
        <div class="card-body">
            <!-- 操作按钮组 -->
            <div class="action-buttons">
                <div>
                    <button type="button" class="btn btn-primary" id="analyzeBtn">
                        分析数据
                        <div id="analyzeSpinner" class="spinner"></div>
                    </button>
                    <span id="analysisStatus" class="dict-status"></span>
                </div>
                <button type="button" class="btn btn-primary" id="loadDataBtn">
                    加载已有数据
                    <div id="loadingSpinner" class="spinner"></div>
                </button>
            </div>

            <div class="row">
                <!-- 左侧文件夹选择区域 -->
                <div class="col-md-3">
                    <!-- 筛选条件区域 - 初始隐藏 -->
                    <div id="filterArea" style="display: none;">
                        <!-- 文件夹选择 -->
                        <div class="card mb-3">
                            <div class="card-header">
                                <h5 class="mb-0">选择被审查人</h5>
                            </div>
                            <div class="card-body">
                                <div id="folderList" class="folder-list">
                                    <!-- 文件夹列表将通过JavaScript动态加载 -->
                                </div>
                            </div>
                        </div>

                        <!-- 关系类型选项 -->
                        <div class="card mb-3">
                            <div class="card-header">
                                <h5 class="mb-0">关系类型</h5>
                            </div>
                            <div class="card-body">
                                <div class="checkbox-group">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="relative" name="relationshipType" value="relative">
                                        <label class="form-check-label text-warning" for="relative">
                                            亲属
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="business" name="relationshipType" value="business">
                                        <label class="form-check-label text-secondary" for="business">
                                            三商(管理服务对象)
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="specific" name="relationshipType" value="specific">
                                        <label class="form-check-label text-success" for="specific">
                                            特定关系人(亲属、三商之外的关系人)
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="company" name="relationshipType" value="company">
                                        <label class="form-check-label text-primary" for="company">
                                            任职单位
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 名称筛选 -->
                        <div class="card mb-3">
                            <div class="card-header">
                                <h5 class="mb-0">名称筛选</h5>
                            </div>
                            <div class="card-body">
                                <input type="text" class="form-control" id="nameFilter" placeholder="请输入名称，将同时匹配名称和交易对方名称">
                            </div>
                        </div>

                        <!-- 筛选按钮组 -->
                        <div class="d-flex justify-content-between mt-3">
                            <button type="button" class="btn btn-primary flex-grow-1 me-2" onclick="applyFilters()">应用筛选</button>
                            <button type="button" class="btn btn-secondary flex-grow-1" onclick="resetFilters()">取消筛选</button>
                        </div>
                    </div>
                </div>
                
                <!-- 右侧内容区域 -->
                <div class="col-md-9">
                    <!-- 汇总表操作按钮 -->
                    <div class="d-flex justify-content-between mb-4">
                        <button type="button" class="btn btn-outline-primary flex-grow-1 me-3" onclick="openFieldSelection('summary')" style="display: none;" id="summaryFieldBtn">选择汇总表字段</button>
                        <button type="button" class="btn btn-outline-primary flex-grow-1" onclick="downloadExcel('summary')" id="summaryDownloadBtn" style="display: none;">下载汇总表</button>
                    </div>

                    <div id="tableContainer" style="display: none;">
                        <!-- 交易汇总表 -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h4 class="mb-0">交易汇总表</h4>
                            </div>
                            <div class="card-body">
                                <div class="table-wrapper">
                                    <div class="table-container">
                                        <div class="scroll-indicator">向右滑动查看更多</div>
                                        <table class="result-table" id="summaryTable">
                                            <thead>
                                                <tr>
                                                    <!-- 表头将通过JavaScript动态生成 -->
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <!-- 数据行将通过JavaScript动态生成 -->
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="pagination-container">
                                        <div id="summary-total-records"></div>
                                        <div class="pagination" id="summary-pagination"></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 明细表按钮组 -->
                        <div class="d-flex justify-content-between mb-4">
                            <button type="button" class="btn btn-outline-primary flex-grow-1 me-3" onclick="openFieldSelection('detail')" style="display: none;" id="detailFieldBtn">选择明细表字段</button>
                            <button type="button" class="btn btn-outline-primary flex-grow-1" onclick="downloadExcel('detail')" id="detailDownloadBtn" style="display: none;">下载明细表</button>
                        </div>

                        <!-- 交易明细表 -->
                        <div class="card">
                            <div class="card-header">
                                <h4 class="mb-0">交易明细表</h4>
                            </div>
                            <div class="card-body">
                                <div class="table-wrapper">
                                    <div class="table-container">
                                        <div class="scroll-indicator">向右滑动查看更多</div>
                                        <table class="result-table" id="detailTable">
                                            <thead>
                                                <tr>
                                                    <!-- 表头将通过JavaScript动态生成 -->
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <!-- 数据行将通过JavaScript动态生成 -->
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="pagination-container">
                                        <div id="detail-total-records"></div>
                                        <div class="pagination" id="detail-pagination"></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                                               </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 字段选择模态框 -->
<div id="fieldSelectionModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">选择显示字段</h3>
            <button type="button" class="modal-close" onclick="closeFieldSelection()">&times;</button>
        </div>
        <div class="modal-body">
            <div class="button-group mb-3">
                <button type="button" class="btn btn-outline-primary btn-sm" onclick="toggleSelectAllFields()">全选/取消全选</button>
            </div>
            <div class="field-selection-grid" id="fieldCheckboxes">
                <!-- 字段选择项将通过JavaScript动态生成 -->
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline-primary" onclick="closeFieldSelection()">取消</button>
            <button type="button" class="btn btn-primary" onclick="applyAndCloseFieldSelection()">确定</button>
        </div>
    </div>
</div>

<!-- 在最底部添加网络图区域 -->
<div id="networkGraphs" class="mt-4" style="display: none;">
    <div class="card">
        <div class="card-header">
            <h4 class="mb-0">关系网络图</h4>
        </div>
        <div class="card-body" id="graphContainer">
            <!-- 网络图将动态插入这里 -->
        </div>
    </div>
</div>

<script>
    // 全局变量
    let currentPage = { summary: 1, detail: 1 };
    let totalPages = { summary: 1, detail: 1 };
    let isLoading = false;
    let availableFields = { summary: [], detail: [] };
    let selectedFields = { summary: [], detail: [] };
    let cachedData = { summary: null, detail: null };
    let itemsPerPage = 20;
    let totalRecords = { summary: 0, detail: 0 };

    // 显示表格数据函数
    function displayTableData(type, data, columns) {
        if (!data || !columns) return;

        const table = document.getElementById(`${type}Table`);
        const totalRecordsDiv = document.getElementById(`${type}-total-records`);
        
        // 生成表头
        const thead = table.querySelector('thead tr');
        thead.innerHTML = columns.map(col => `<th>${col}</th>`).join('');
        
        // 生成数据行
        const tbody = table.querySelector('tbody');
        tbody.innerHTML = '';
        
        const start = (currentPage[type] - 1) * itemsPerPage;
        const end = Math.min(start + itemsPerPage, data.length);
        
        for (let i = start; i < end; i++) {
            const row = data[i];
            const tr = document.createElement('tr');
            tr.innerHTML = columns.map(col => {
                const value = row[col];
                let displayValue = '';
                
                if (value === null || value === undefined) {
                    displayValue = '';
                } else if (typeof value === 'number') {
                    displayValue = value.toFixed(2);
                } else {
                    displayValue = value.toString();
                }
                
                return `<td title="${displayValue}">${displayValue}</td>`;
            }).join('');
            tbody.appendChild(tr);
        }
        
        // 更新总记录数显示
        if (totalRecordsDiv) {
            totalRecordsDiv.textContent = `共 ${data.length} 条记录`;
        }
        
        // 更新分页信息
        totalRecords[type] = data.length;
        updatePaginationInfo(type);
    }

    // 更新分页信息
    function updatePaginationInfo(type) {
        const maxPage = Math.ceil(totalRecords[type] / itemsPerPage);
        updatePagination(type, maxPage);
    }

    // 更新分页控件
    function updatePagination(type, maxPage) {
        const pagination = document.getElementById(`${type}-pagination`);
        pagination.innerHTML = '';

        // 上一页按钮
        const prevButton = document.createElement('button');
        prevButton.textContent = '上一页';
        prevButton.disabled = currentPage[type] === 1;
        prevButton.onclick = () => {
            if (currentPage[type] > 1) {
                currentPage[type]--;
                displayTableData(type, cachedData[type], selectedFields[type].map(f => f.id));
            }
        };
        pagination.appendChild(prevButton);

        // 页码按钮
        let startPage = Math.max(1, currentPage[type] - 2);
        let endPage = Math.min(maxPage, currentPage[type] + 2);

        if (endPage - startPage < 4) {
            if (currentPage[type] < maxPage / 2) {
                endPage = Math.min(startPage + 4, maxPage);
            } else {
                startPage = Math.max(endPage - 4, 1);
            }
        }

        // 第一页
        if (startPage > 1) {
            const firstButton = document.createElement('button');
            firstButton.textContent = '1';
            firstButton.onclick = () => {
                currentPage[type] = 1;
                displayTableData(type, cachedData[type], selectedFields[type].map(f => f.id));
            };
            pagination.appendChild(firstButton);

            if (startPage > 2) {
                const ellipsis = document.createElement('span');
                ellipsis.textContent = '...';
                ellipsis.className = 'pagination-ellipsis';
                pagination.appendChild(ellipsis);
            }
        }

        // 中间页码
        for (let i = startPage; i <= endPage; i++) {
            const pageButton = document.createElement('button');
            pageButton.textContent = i;
            pageButton.classList.toggle('active', i === currentPage[type]);
            pageButton.onclick = () => {
                currentPage[type] = i;
                displayTableData(type, cachedData[type], selectedFields[type].map(f => f.id));
            };
            pagination.appendChild(pageButton);
        }

        // 最后一页
        if (endPage < maxPage) {
            if (endPage < maxPage - 1) {
                const ellipsis = document.createElement('span');
                ellipsis.textContent = '...';
                ellipsis.className = 'pagination-ellipsis';
                pagination.appendChild(ellipsis);
            }

            const lastButton = document.createElement('button');
            lastButton.textContent = maxPage;
            lastButton.onclick = () => {
                currentPage[type] = maxPage;
                displayTableData(type, cachedData[type], selectedFields[type].map(f => f.id));
            };
            pagination.appendChild(lastButton);
        }

        // 下一页按钮
        const nextButton = document.createElement('button');
        nextButton.textContent = '下一页';
        nextButton.disabled = currentPage[type] === maxPage;
        nextButton.onclick = () => {
            if (currentPage[type] < maxPage) {
                currentPage[type]++;
                displayTableData(type, cachedData[type], selectedFields[type].map(f => f.id));
            }
        };
        pagination.appendChild(nextButton);
    }

    // 字段选择相关函数
    function openFieldSelection(type) {
        const modal = document.getElementById('fieldSelectionModal');
        modal.classList.add('visible');
        modal.dataset.type = type; // 存储当前操作的表格类型
        
        // 更新模态框标题
        const modalTitle = modal.querySelector('.modal-title');
        modalTitle.textContent = type === 'summary' ? '选择汇总表字段' : '选择明细表字段';
        
        initializeFieldSelection(type);
    }

    function closeFieldSelection() {
        const modal = document.getElementById('fieldSelectionModal');
        modal.classList.remove('visible');
        delete modal.dataset.type;
    }

    function initializeFieldSelection(type) {
        const container = document.getElementById('fieldCheckboxes');
        container.innerHTML = '';
        
        // 确保availableFields[type]存在
        if (!availableFields[type]) {
            console.error('No available fields for type:', type);
            return;
        }
        
        availableFields[type].forEach(field => {
            const div = document.createElement('div');
            div.className = 'field-checkbox';
            const isChecked = selectedFields[type].some(f => f.id === field.id);
            div.innerHTML = `
                <input type="checkbox" id="field_${field.id}" 
                       ${isChecked ? 'checked' : ''}>
                <label for="field_${field.id}">${field.name}</label>
            `;
            container.appendChild(div);
        });
    }

    function toggleSelectAllFields() {
        const modal = document.getElementById('fieldSelectionModal');
        const type = modal.dataset.type;
        const checkboxes = document.querySelectorAll('#fieldCheckboxes input[type="checkbox"]');
        const allChecked = Array.from(checkboxes).every(cb => cb.checked);
        checkboxes.forEach(checkbox => checkbox.checked = !allChecked);
    }

    function applyFieldSelection() {
        const modal = document.getElementById('fieldSelectionModal');
        const type = modal.dataset.type;
        const checkboxes = document.querySelectorAll('#fieldCheckboxes input[type="checkbox"]:checked');
        
        // 获取选中的字段
        const newSelectedFields = Array.from(checkboxes).map(cb => {
            const fieldId = cb.id.replace('field_', '');
            return availableFields[type].find(f => f.id === fieldId);
        }).filter(Boolean); // 过滤掉undefined
        
        if (newSelectedFields.length === 0) {
            alert('请至少选择一个字段');
            return false;
        }
        
        // 更新选中的字段
        selectedFields[type] = newSelectedFields;
        
        // 重新加载数据时保持筛选条件
        const params = new URLSearchParams();
        selectedFields[type].forEach(field => {
            params.append('fields', field.id);
        });
        params.append('type', type);
        
        // 添加当前的筛选条件
        const selectedFolders = Array.from(document.querySelectorAll('#folderList input[type="checkbox"]:checked'))
            .map(cb => cb.value);
        const selectedRelationshipTypes = Array.from(document.querySelectorAll('input[name="relationshipType"]:checked'))
            .map(cb => cb.value);
        const nameFilter = document.getElementById('nameFilter').value.trim();
        
        selectedFolders.forEach(folder => params.append('folders', folder));
        selectedRelationshipTypes.forEach(type => params.append('relationshipTypes', type));
        if (nameFilter) {
            params.append('nameFilter', nameFilter);
        }
        
        fetch(`/personnel-network/get-analysis-data?${params.toString()}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayTableData(type, data.data, selectedFields[type].map(f => f.id));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('更新数据时出错');
            });
            
        return true;
    }

    function applyAndCloseFieldSelection() {
        if (applyFieldSelection()) {
            closeFieldSelection();
        }
    }

    function downloadExcel(type) {
        if (selectedFields[type].length === 0) {
            alert('请至少选择一个字段');
            return;
        }

        const params = new URLSearchParams();
        selectedFields[type].forEach(field => params.append('fields', field.id));

        // 添加筛选条件
        const selectedFolders = Array.from(document.querySelectorAll('#folderList input[type="checkbox"]:checked'))
            .map(cb => cb.value);
        const selectedRelationshipTypes = Array.from(document.querySelectorAll('input[name="relationshipType"]:checked'))
            .map(cb => cb.value);
        const nameFilter = document.getElementById('nameFilter').value.trim();

        selectedFolders.forEach(folder => params.append('folders', folder));
        selectedRelationshipTypes.forEach(type => params.append('relationshipTypes', type));
        if (nameFilter) {
            params.append('nameFilter', nameFilter);
        }
        params.append('type', type);
        
        const downloadUrl = `/personnel-network/download-excel?${params.toString()}`;
        
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    // 修改加载分析结果数据函数
    async function loadAnalysisData(applyFilter = false, nameFilter = '') {
        try {
            loadingSpinner.style.display = 'inline-block';
            document.getElementById('loadDataBtn').disabled = true;

            // 获取选中的文件夹和关系类型
            const params = new URLSearchParams();
            
            if (applyFilter) {
                // 获取选中的文件夹
                const selectedFolders = Array.from(document.querySelectorAll('#folderList input[type="checkbox"]:checked'))
                    .map(cb => cb.value);
                selectedFolders.forEach(folder => params.append('folders', folder));

                // 获取选中的关系类型
                const selectedRelationshipTypes = Array.from(document.querySelectorAll('input[name="relationshipType"]:checked'))
                    .map(cb => cb.value);
                selectedRelationshipTypes.forEach(type => params.append('relationshipTypes', type));

                // 添加名称筛选
                if (nameFilter) {
                    params.append('nameFilter', nameFilter);
                }
            }

            // 获取汇总数据
            const summaryResponse = await fetch(`/personnel-network/get-analysis-data?type=summary&${params.toString()}`);
            const summaryData = await summaryResponse.json();
            
            // 获取明细数据
            const detailResponse = await fetch(`/personnel-network/get-analysis-data?type=detail&${params.toString()}`);
            const detailData = await detailResponse.json();

            // 显示筛选区域
            document.getElementById('filterArea').style.display = 'block';
            
            // 检查是否有数据
            if ((!summaryData.success || !summaryData.data || summaryData.data.length === 0) && 
                (!detailData.success || !detailData.data || detailData.data.length === 0)) {
                // 如果没有数据，显示提示信息
                document.getElementById('tableContainer').style.display = 'none';
                showNoDataMessage(applyFilter);
                return;
            }

            // 有数据时隐藏提示信息
            hideNoDataMessage();
            
            // 显示表格容器
            document.getElementById('tableContainer').style.display = 'block';
            
            if (summaryData.success) {
                cachedData.summary = summaryData.data;
                availableFields.summary = summaryData.columns.map(column => ({
                    id: column,
                    name: column
                }));
                selectedFields.summary = [...availableFields.summary];
            }
            
            if (detailData.success) {
                cachedData.detail = detailData.data;
                availableFields.detail = detailData.columns.map(column => ({
                    id: column,
                    name: column
                }));
                selectedFields.detail = [...availableFields.detail];
            }
            
            // 显示字段选择和下载按钮
            document.getElementById('summaryFieldBtn').style.display = 'inline-block';
            document.getElementById('summaryDownloadBtn').style.display = 'inline-block';
            document.getElementById('detailFieldBtn').style.display = 'inline-block';
            document.getElementById('detailDownloadBtn').style.display = 'inline-block';
            
            // 重置页码并显示数据
            currentPage.summary = 1;
            currentPage.detail = 1;
            
            if (summaryData.success) {
                displayTableData('summary', summaryData.data, summaryData.columns);
            }
            if (detailData.success) {
                displayTableData('detail', detailData.data, detailData.columns);
            }

            // 更新状态为已存在数据
            updateAnalysisStatus('exists');

            // 清空现有的图表容器
            document.getElementById('graphContainer').innerHTML = '';
            
            // 显示网络图区域
            document.getElementById('networkGraphs').style.display = 'block';

            // 按文件夹分组显示网络图
            const folderGroups = {};
            if (summaryData.success && summaryData.data) {
                summaryData.data.forEach(record => {
                    const folder = record['文件夹'];
                    if (!folderGroups[folder]) {
                        folderGroups[folder] = [];
                    }
                    folderGroups[folder].push(record);
                });

                // 为每个文件夹创建网络图
                for (const [folder, data] of Object.entries(folderGroups)) {
                    await drawNetworkGraph(data, folder);
                }
            }
            } catch (error) {
            console.error('Error:', error);
            // 显示错误提示
            const errorDiv = document.createElement('div');
            errorDiv.className = 'alert alert-danger';
            errorDiv.textContent = '加载数据时出错，请刷新页面重试';
            document.getElementById('graphContainer').appendChild(errorDiv);
        } finally {
            loadingSpinner.style.display = 'none';
            document.getElementById('loadDataBtn').disabled = false;
        }
    }

    // 显示无数据提示信息
    function showNoDataMessage(isFiltered) {
        const tableContainer = document.getElementById('tableContainer');
        const message = isFiltered ? '没有符合筛选条件的数据' : '暂无数据';
        
        // 如果提示容器不存在，创建一个新的
        let noDataMessage = document.getElementById('noDataMessage');
        if (!noDataMessage) {
            noDataMessage = document.createElement('div');
            noDataMessage.id = 'noDataMessage';
            noDataMessage.className = 'card mt-3';
            noDataMessage.innerHTML = `
                <div class="card-body text-center">
                    <h5 class="text-muted">${message}</h5>
                </div>
            `;
            // 将提示信息插入到表格容器之前
            tableContainer.parentNode.insertBefore(noDataMessage, tableContainer);
        } else {
            noDataMessage.querySelector('h5').textContent = message;
            noDataMessage.style.display = 'block';
        }
    }

    // 隐藏无数据提示信息
    function hideNoDataMessage() {
        const noDataMessage = document.getElementById('noDataMessage');
        if (noDataMessage) {
            noDataMessage.style.display = 'none';
        }
    }

    // 修改应用筛选函数
    function applyFilters() {
        // 检查是否有选择文件夹
        const selectedFolders = Array.from(document.querySelectorAll('#folderList input[type="checkbox"]:checked'));
        if (selectedFolders.length === 0) {
            alert('请至少选择一个被审查人');
            return;
        }

        // 检查是否有选择关系类型
        const selectedRelationshipTypes = Array.from(document.querySelectorAll('input[name="relationshipType"]:checked'));
        if (selectedRelationshipTypes.length === 0) {
            alert('请至少选择一种关系类型');
            return;
        }

        // 获取名称筛选值
        const nameFilter = document.getElementById('nameFilter').value.trim();

        loadAnalysisData(true, nameFilter);
    }

    // 修改重置筛选函数
    function resetFilters() {
        // 取消所有文件夹的选择
        document.querySelectorAll('#folderList input[type="checkbox"]').forEach(checkbox => {
            checkbox.checked = false;
        });

        // 取消所有关系类型的选择
        document.querySelectorAll('input[name="relationshipType"]').forEach(checkbox => {
            checkbox.checked = false;
        });

        // 清空名称筛选
        document.getElementById('nameFilter').value = '';

        // 重新加载数据（不带筛选条件）
        loadAnalysisData(false);
    }

    // 移除自动筛选的事件监听
    function addFilterChangeListeners() {
        // 不再需要自动触发筛选
    }

        // 更新分析状态显示
        function updateAnalysisStatus(status) {
        const analysisStatus = document.getElementById('analysisStatus');
            switch(status) {
                case 'exists':
                    analysisStatus.textContent = '已存在数据';
                    analysisStatus.className = 'dict-status exists';
                    break;
                case 'not-exists':
                    analysisStatus.textContent = '暂无数据';
                    analysisStatus.className = 'dict-status not-exists';
                    break;
                case 'analyzing':
                    analysisStatus.textContent = '分析中...';
                    analysisStatus.className = 'dict-status generating';
                    break;
            }
        }

    // 页面加载完成后执行的代码
    document.addEventListener('DOMContentLoaded', function() {
        const filterArea = document.getElementById('filterArea');
        const tableContainer = document.getElementById('tableContainer');
        const loadDataBtn = document.getElementById('loadDataBtn');
        const analyzeBtn = document.getElementById('analyzeBtn');
        const loadingSpinner = document.getElementById('loadingSpinner');
        const analyzeSpinner = document.getElementById('analyzeSpinner');
        const analysisStatus = document.getElementById('analysisStatus');

        // 初始化文件夹列表
        async function initializeFolders() {
            try {
                // 获取所有文件夹
                const foldersResponse = await fetch('/personnel-network/get-folders');
                const foldersData = await foldersResponse.json();
                
                if (foldersData.error) {
                    alert(foldersData.error);
                    return;
                }

                // 更新文件夹列表
                const folderList = document.getElementById('folderList');
                folderList.innerHTML = foldersData.folders.map(folder => `
                    <div class="folder-item">
                        <div class="folder-item-left">
                            <input type="checkbox" id="${folder}" name="folder" value="${folder}">
                            <label for="${folder}">${folder}</label>
                        </div>
                        <span class="folder-status">检查中...</span>
                    </div>
                `).join('');

                // 检查每个文件夹的状态
                await checkFolderStatus();

                // 添加筛选条件变化监听
                addFilterChangeListeners();
            } catch (error) {
                console.error('Error initializing folders:', error);
            }
        }

        // 检查分析状态
        async function checkAnalysisStatus() {
            try {
                const response = await fetch('/personnel-network/check-analysis-results');
                const result = await response.json();
                updateAnalysisStatus(result.all_complete ? 'exists' : 'not-exists');
            } catch (error) {
                console.error('Error checking analysis status:', error);
                updateAnalysisStatus('not-exists');
            }
        }

        // 检查文件夹状态
        async function checkFolderStatus() {
            try {
                const response = await fetch('/personnel-network/check-analysis-results');
                const data = await response.json();
                
                if (data.results) {
                    const folderList = document.getElementById('folderList');
                    if (folderList) {
                        const folderItems = folderList.querySelectorAll('.folder-item');
                        folderItems.forEach(item => {
                            const folderId = item.querySelector('input[type="checkbox"]').value;
                            const statusSpan = item.querySelector('.folder-status');
                            if (statusSpan) {
                                const exists = data.results[folderId];
                                statusSpan.textContent = exists ? '已分析' : '未分析';
                                statusSpan.className = `folder-status ${exists ? 'exists' : 'not-exists'}`;
                            }
                        });
                    }
                }
            } catch (error) {
                console.error('Error checking folder status:', error);
            }
        }

        // 生成分析
        async function generateAnalysis() {
            try {
                analyzeSpinner.style.display = 'inline-block';
                analyzeBtn.disabled = true;
                
                // 更新状态为分析中
                updateAnalysisStatus('analyzing');

                const response = await fetch('/personnel-network/generate-analysis', {
                    method: 'POST',
                });
                const data = await response.json();
                
                if (data.success) {
                    alert('分析完成！');
                    await checkFolderStatus(); // 更新文件夹状态
                    loadAnalysisData(); // 重新加载数据
                } else {
                    alert('分析失败：' + data.error);
                    updateAnalysisStatus('not-exists');
                }
            } catch (error) {
                console.error('Error:', error);
                alert('分析过程中出现错误');
                updateAnalysisStatus('not-exists');
            } finally {
                analyzeSpinner.style.display = 'none';
                analyzeBtn.disabled = false;
            }
        }

        // 初始化时检查分析状态
        checkAnalysisStatus();

        // 绑定按钮事件
        loadDataBtn.addEventListener('click', loadAnalysisData);
        analyzeBtn.addEventListener('click', generateAnalysis);

        // 初始化文件夹列表
        initializeFolders();
    });

    async function drawNetworkGraph(data, folderName) {
        try {
            // 为每个图表创建容器
            const graphDiv = document.createElement('div');
            graphDiv.className = 'card mb-4';
            graphDiv.innerHTML = `
                <div class="card-header">
                    <h5 class="mb-0">${folderName} - 关系网络图</h5>
                </div>
                <div class="card-body">
                    <div id="graph_${folderName}" style="width: 100%; height: 600px;"></div>
                </div>
            `;
            document.getElementById('graphContainer').appendChild(graphDiv);

            const chartDom = document.getElementById(`graph_${folderName}`);
            const myChart = echarts.init(chartDom);
            
            const networkData = generateNetworkData(data, folderName);
            
            const option = {
                title: {
                    text: `${folderName} - 人员关系网络图`,
                    top: 'top',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        if (params.dataType === 'edge') {
                            const direction = params.data.value >= 0 ? '流出' : '流入';
                            return `${params.data.source} ${direction} ${params.data.target}<br/>
                                    关系: ${params.data.name}<br/>
                                    交易金额: ${Math.abs(params.data.value).toLocaleString()} 元<br/>
                                    ${params.data.company ? '所属公司: ' + params.data.company : ''}`;
                        }
                        return `${params.name}<br/>
                                类型: ${networkData.categories[params.data.category].name}<br/>
                                ${params.data.company ? '所属公司: ' + params.data.company : ''}`;
                    }
                },
                legend: {
                    data: networkData.categories.map(cat => cat.name),
                    orient: 'vertical',
                    left: 'left',
                    top: 'middle'
                },
                series: [{
                    type: 'graph',
                    layout: 'force',
                    data: networkData.nodes,
                    links: networkData.edges,
                    categories: networkData.categories,
                    roam: true,
                    label: {
                        show: true,
                        position: 'right',
                        formatter: '{b}'
                    },
                    edgeLabel: {
                        show: true,
                        formatter: function(params) {
                            return Math.abs(params.data.value).toLocaleString() + '元';
                        },
                        fontSize: 12,
                        padding: [5, 7],
                        backgroundColor: '#fff',
                        borderRadius: 4,
                        borderWidth: 1,
                        borderColor: '#ddd'
                    },
                    force: {
                        repulsion: 1500,
                        edgeLength: 300
                    },
                    emphasis: {
                        focus: 'adjacency'
                    },
                    lineStyle: {
                        color: '#FF0000',  // 设置线的颜色为红色
                        curveness: 0.3
                    }
                }]
            };
            
            myChart.setOption(option);
            
            // 自适应大小
            window.addEventListener('resize', () => {
                myChart.resize();
            });
        } catch (error) {
            console.error('Failed to draw network graph:', error);
            const errorDiv = document.createElement('div');
            errorDiv.className = 'alert alert-danger';
            errorDiv.textContent = '加载关系网络图失败，请刷新页面重试';
            document.getElementById('graphContainer').appendChild(errorDiv);
        }
    }

    function generateNetworkData(summaryData, folderName) {
        const nodes = new Set();
        const edges = [];
        const nodeData = [];
        const categories = [
            { name: '亲属' },
            { name: '三商清单' },
            { name: '特定关系人' },
            { name: '任职单位' }
        ];

        // 首先添加本人节点
        nodeData.push({
            name: folderName,  // 文件夹名称就是本人名称
            category: 0,  // 使用亲属类别
            symbolSize: 70,  // 本人节点稍大一些
            itemStyle: {
                color: '#FF6B6B'  // 本人节点使用特殊颜色
            }
        });
        nodes.add(folderName);

        // 处理数据，生成节点和边
        summaryData.forEach(record => {
            const source = record['名称'];
            const target = record['交易对方名称'];
            const relationship = record['关系'];
            const relationshipType = record['关系类型'];
            const amount = record['净转出差额'];
            const company = record['所属公司名称'] || '';

            // 添加其他节点（排除已添加的本人节点）
            if (!nodes.has(source)) {
                nodes.add(source);
                nodeData.push({
                    name: source,
                    category: categories.findIndex(cat => cat.name === relationshipType),
                    value: amount,
                    company: company,
                    symbolSize: 50
                });
            }
            if (!nodes.has(target)) {
                nodes.add(target);
                nodeData.push({
                    name: target,
                    category: categories.findIndex(cat => cat.name === relationshipType),
                    value: amount,
                    company: company,
                    symbolSize: 50
                });
            }

            // 添加边
            edges.push({
                source: source,
                target: target,
                value: amount,
                name: relationship,
                company: company,
                symbol: ['none', 'arrow'],
                symbolSize: [10, 15],
                lineStyle: {
                    width: Math.log(Math.abs(amount) + 1),
                    type: 'solid',
                    curveness: 0.3,
                    color: '#FF0000'  // 设置线的颜色为红色
                },
                label: {
                    show: true,
                    formatter: Math.abs(amount).toLocaleString() + '元'
                }
            });
        });

        return {
            nodes: nodeData,
            edges: edges,
            categories: categories
        };
    }
</script>
{% endblock %} 